<template>
  <div class="rightArea h">
    <!-- 聊天头部 -->
    <div class="header flex vcenter between" >
      <div style="margin-left:5%">{{$store.state.chackChatUser.remarksName}}</div>
      <i class="el-icon-more" style="margin-right:2%"></i>
    </div>
    <!-- 聊天框 -->
    <div class="chatBox">
      <div class="chatContent">
        <el-scrollbar ref="myScrollbar" wrap-style="overflow-x:hidden;" class="h">
          <div v-for="(item, index) in chatRecord" :key="index">
            <div v-if="item.sendUser == $store.state.chackChatUser.account" class="flex" style="margin: 10px 20px 10px 20px;">
              <el-avatar shape="square" size="medium" icon="el-icon-user-solid"></el-avatar>
              <div v-if="item.chatRecordType == 'text'" class="chat-bubble chat-bubble-left chat-left-color" v-html="item.chatRecord"></div>
              <div v-else-if="item.chatRecordType == 'files'">
                <div class="filesRecord pointer chat-bubble chat-bubble-left chat-left-color" @click="downloadFiles(item.chatRecord)">
                  <div class="flex between">
                    <div>{{item.chatRecord.substring(item.chatRecord.lastIndexOf('-') + 1, item.chatRecord.length)}}</div>
                    <i class="el-icon-document" style="font-size:46px;color:orange;"></i>
                  </div>
                  <footer class="m5 fsmallFont grayText topBorder">仿·微信网页版</footer>
                </div>
              </div>
            </div>
            <div v-else-if="item.sendUser == $store.state.chatUserInfo.account" class="flex" style="margin: 10px 20px 10px 20px;justify-content: flex-end">
              <div v-if="item.chatRecordType == 'text'" class="chat-bubble chat-bubble-right chat-right-color" v-html="item.chatRecord"></div>
              <div v-else-if="item.chatRecordType == 'files'">
                <div class="filesRecord pointer chat-bubble chat-bubble-right chat-right-color" @click="downloadFiles(item.chatRecord)">
                  <div class="m10 flex between vcenter">
                    <div>{{item.chatRecord.substring(item.chatRecord.lastIndexOf('-') + 1, item.chatRecord.length)}}</div>
                    <i class="el-icon-document" style="font-size:46px;color:orange;"></i>
                  </div>
                  <footer class="m5 smallFont grayText topBorder">仿·微信网页版</footer>
                </div>
              </div>
              <el-avatar shape="square" size="medium" icon="el-icon-user-solid"></el-avatar>
            </div>
          </div>
        </el-scrollbar>
      </div>

      <div class="chatInput">
        <div class="chatIconBar w flex vcenter">
          <i @click="openEmoticons()" class="pointer el-icon-picture-outline-round" style="margin-left: 20px;"></i>
          
          <el-upload
            ref="uploadFiles"
            action="http://localhost:3000/user/uploadFiles"
            :limit='1' :show-file-list='false' :auto-upload='true'
            :on-success="handleAvatarSuccess"
            class="files"
          >
            <i class="pointer el-icon-folder"></i>
          </el-upload>
          <i @click="toImage()" class="pointer el-icon-scissors" style="margin-left: 20px;"></i>
          <i class="pointer el-icon-chat-dot-round" style="margin-left: 20px;"></i>
        </div>

        <Emoticon ref="emoticon" @AppendInputValue="AppendMessageText"></Emoticon>

        <el-scrollbar ref="chatScrollbar" wrap-style="overflow-x:hidden;" style="height:60px;">
          <div
            contenteditable="true"
            ref="inputMsg"
            v-on:input="handleInput"
            @keyup.ctrl.enter="sendMessage"
            class="divInput"
          ></div> 
        </el-scrollbar>

        <div class="sendBtn flex vcenter"><el-button @click="sendMessage" type="success" plain>发送(ce)</el-button></div>
      </div>
    </div>
  </div>
</template>

<script>
import Emoticon from './emoticon.vue'
import html2canvas from 'html2canvas'
export default {
  data() {
    return {
      visible: true,
      chatRecord: [],
      waitSendMessage: '',
    }
  },
  components:{ Emoticon },
  mounted() {
    this.getChatRecord()
  },
  updated() {
    this.scrollDown()
  },  
  computed: {
    jtData() {
      return this.$store.state.chackChatUser.remarksName;
    },
  },
  watch:{
    jtData: {
      handler(nval, oval) {
        // console.log(nval, oval);//nval改变后的新数据，oval改变前的旧数据
        this.getChatRecord()
      },
      deep: true, // 深度监听
      immediate: true,//立即执行
    },
  },
  methods: {
    getChatRecord(){
      this.$axios.post('http://localhost:3000/user/getChatRecord', { userData: this.$store.state.chatUserInfo, chackUserData: this.$store.state.chackChatUser, })
        .then((res) => {
          // console.log(res);
          this.chatRecord = res.data.chatRecord
        })
    },
    sendMessage(){
      this.$axios.post('http://localhost:3000/user/sendMessage', { userData: this.$store.state.chatUserInfo, chackUserData: this.$store.state.chackChatUser, sendMessage: this.waitSendMessage })
        .then((res) => {
          // console.log(res);
          this.waitSendMessage = ''
          this.$refs.inputMsg.innerHTML = ''
          this.getChatRecord()
        })
    },
    scrollDown() {
      this.$refs['myScrollbar'].wrap.scrollTop = this.$refs['myScrollbar'].wrap.scrollHeight
    },
    handleInput(){
      this.waitSendMessage = this.$refs.inputMsg.innerHTML;
    },

    // 打开表情包弹框
    openEmoticons() {
      this.$refs.emoticon.openEmoticon();
    },
    AppendMessageText(EmotionChinese) {
      this.$refs.inputMsg.innerHTML += EmotionChinese
      this.waitSendMessage += EmotionChinese;
    },
    // 截图
    toImage () {
      const canvas = document.createElement('canvas')
      const canvasBox = document.querySelector('.chatContent')
      const width = canvasBox.clientWidth
      const height = canvasBox.clientHeight
      // 宽高 * 2 并放大 2 倍 是为了防止图片模糊
      canvas.width = width * 2
      canvas.height = height * 2
      canvas.width = width
      canvas.height = height
      canvas.style.width = width + 'px'
      canvas.style.height = height + 'px'
      const context = canvas.getContext('2d')
      // context.scale(2, 2)
      context.scale(1, 1)
      const options = {
        backgroundColor: null,
        canvas: canvas,
        useCORS: true
      }
      html2canvas(canvasBox, options).then((canvas) => {
        const dataURL = canvas.toDataURL('image/png') // 图片格式转成base64
        this.downloadImage(dataURL)
      })
    },
    downloadImage (url) {
      this.$refs.inputMsg.innerHTML += "<img src='" + url + "' >"
      this.waitSendMessage += "<img src='" + url + "' >"
      // const img = document.createElement('img')
      // img.src = url
      // a.download = '图片命名'
      // a.click()
    },

    // 上传文件
    handleAvatarSuccess(res) {   
      // console.log(res);
      this.$axios.post('http://localhost:3000/user/editFilesDetail', { 
        userData: this.$store.state.chatUserInfo, 
        chackUserData: this.$store.state.chackChatUser, 
        name: res.name,
        path: res.path,
      })
        .then((res) => {
          console.log(res);
          this.$refs.uploadFiles.clearFiles();
          this.waitSendMessage = res.data.sendMessage
          this.sendMessage()
        })
      
    },
    // 下载文件
    downloadFiles(path){
      this.$axios.post('http://localhost:3000/user/downloadFiles', { fileId: path.split('-')[1],  userData: this.$store.state.chatUserInfo })
        .then((res) => {
          console.log(res);
          const a = document.createElement('a')
          a.href =  res.data.filesData.fileRoute
          a.download = res.data.filesData.fileName
          console.log(a);
          a.click()
        })
    },
  }
}
</script>

<style>
.chatBox{
  width: 100%;
  height: 90%;
  border-top: 1px solid rgb(214, 214, 214);
}
.chatContent{
  width: 100%;
  height: 75%;
}
.chatInput{
  width: 100%;
  height: 25%;
  border-top: 1px solid rgb(214, 214, 214, 0.7);
}
.chatIconBar{
  height: 25%;
  font-size: 20px;
  color: rgb(97, 97, 97);
}
.divInput{
  margin: 0 20px;
  min-height: 60px;
  max-height: 60px;
  min-width: 566.54px;
  max-width: 566.54px;
  line-height: 20px;
  outline: none;
  word-wrap:break-word;
}
.divInput img{
  max-width: 200px;
}
.sendBtn{
  justify-content: flex-end;
  margin-right: 5%;
}
.files{
  margin-left: 20px;
}
.filesRecord{
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 220px;
  height: 95px;
  background-color: white !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
}
.filesRecord:hover{
  background-color: rgb(235, 235, 235) !important;
}
.filesRecord.chat-bubble-right::after{
  border-left: 7px solid white !important;
}
.filesRecord:hover.chat-bubble-right::after{
  border-left: 7px solid rgb(235, 235, 235) !important;
}

.el-textarea__inner{
  border: 0;
  background-color: rgba(0, 0, 0, 0);
}
.el-textarea__inner:hover{
  border: 0;
}
.el-upload-dragger{
  width: 20px;
  height: 20px;
  border: 0;
  background-color: rgba(0, 0, 0, 0);
  overflow: visible;
  cursor: auto;
}

.chat-bubble{
  position: relative;
  margin: 0 15px;
  padding: 5px 10px;
  max-width: 300px;
  min-height: 20px;
  line-height: 20px;
  word-wrap:break-word;
  border-radius: 5px;
}
.chat-bubble-left::before {
  content: '';
  position: absolute;
  width: 0;
  height: 0;

  top: 10px;
  left: -8px;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
}
.chat-bubble-left::after{
  content: '';
  position: absolute;
  width: 0;
  height: 0;

  top: 10px;
  left: -7px;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
  border-right: 8px solid rgb(255, 255, 255);
}
.chat-left-color{
  background-color: rgb(255, 255, 255);
}
.chat-bubble-right::before {
  content: '';
  position: absolute;
  width: 0;
  height: 0;

  top: 10px;
  right: -8px;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
}
.chat-bubble-right::after{
  content: '';
  position: absolute;
  width: 0;
  height: 0;

  top: 10px;
  right: -7px;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
  border-left: 7px solid rgb(94, 227, 87);
}
.chat-right-color{
  background-color: rgb(94, 227, 87);
}
.chat-bubble img{
  max-width: 300px;
}
</style>